package com.lb.shopguide.ui.fragment.guide.pay;

import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.JsonArray;
import com.google.gson.internal.LinkedTreeMap;
import com.lb.baselib.http.ResponseCode;
import com.lb.baselib.http.SimpleLbObserver;
import com.lb.baselib.http.bean.BaseResponse;
import com.lb.shopguide.R;
import com.lb.shopguide.adapter.AdapterMyMoney;
import com.lb.shopguide.base.BaseCommonFragment;
import com.lb.shopguide.constants.AppConstant;
import com.lb.shopguide.entity.AlipayAccountBean;
import com.lb.shopguide.entity.GuideBalanceBean;
import com.lb.shopguide.entity.GuideMonthlyBalance;
import com.lb.shopguide.event.guide.AlipayAccountChangeEvent;
import com.lb.shopguide.event.guide.GuideDivideUpdateEvent;
import com.lb.shopguide.event.guide.UserBeanEvent;
import com.lb.shopguide.http.method.ApiMethodGuide;
import com.lb.baselib.http.SimpleObserverOnNextListener;
import com.lb.shopguide.ui.activity.GuideMainActivity;
import com.lb.shopguide.ui.view.LbFontTextView;
import com.lb.shopguide.ui.view.NormalTitleBar;
import com.lb.shopguide.util.json.JsonUtil;
import com.trello.rxlifecycle2.android.FragmentEvent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.zakariya.stickyheaders.StickyHeaderLayoutManager;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by kang on 2017/9/6.
 */

public class FragmentMyMoney extends BaseCommonFragment {
    @BindView(R.id.ntb)
    NormalTitleBar ntb;
    @BindView(R.id.tv_total_money)
    LbFontTextView tvTotalMoney;
    @BindView(R.id.tv_status)
    TextView tvStatus;
    @BindView(R.id.layout_alipay_setting)
    RelativeLayout layoutAlipaySetting;
    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;

    private AdapterMyMoney mAdapterMyMoney;
    private List<GuideMonthlyBalance> moneyMonthBeans;

    private AlipayAccountBean accountBean;
    private String balance;

    public static FragmentMyMoney newInstance(String accountBalance) {
        FragmentMyMoney fragment = new FragmentMyMoney();
        Bundle bundle = new Bundle();
        bundle.putString(AppConstant.ACCOUNT_BALANCE, accountBalance);
        fragment.setArguments(bundle);
        return fragment;
    }



    @Override
    public int getLayoutId() {
        return R.layout.fragment_my_money;
    }

    @Override
    public void initData() {
        moneyMonthBeans = new ArrayList<>();
        Bundle bundle = getArguments();
        if (bundle.containsKey(AppConstant.ACCOUNT_BALANCE)) {
            balance = bundle.getString(AppConstant.ACCOUNT_BALANCE);
        }

        sendRequestGetMoneyList();
        sendRequestGetAlipayAccount();
        EventBus.getDefault().register(this);
    }

    @Override
    public void initView() {
        noDataView = view.findViewById(R.id.layout_empty);
        TextView tvEmpty = noDataView.findViewById(R.id.tv_empty);
        tvEmpty.setText("暂时没有记录");

        ntb.setTitleText("我的钱包");
        ntb.setTitleColor(getResources().getColor(R.color.white));
        ntb.setLeftImageSrc(R.drawable.iv_back_white);
        ntb.setBackground(getResources().getColor(R.color.sg_common_red));

        layoutAlipaySetting.setClickable(false);
        bindData();
    }

    @Override
    public void finishRefresh() {

    }

    @Override
    public void sessionOutOfDate() {
        ((GuideMainActivity) getActivity()).onSessionOutOfDate();
    }

    @Override
    public void requestError(String error) {
        ToastUtils.showShort(error);
    }

    @Override
    public String getPageTag() {
        return FragmentMyMoney.class.getName();
    }

    private void bindData() {
        tvTotalMoney.setText(balance);
    }

    private void sendRequestGetMoneyList() {
        moneyMonthBeans.clear();
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    LinkedTreeMap<String, String> map = (LinkedTreeMap<String, String>) response.getReturnContent();
                    Iterator<String> it = map.keySet().iterator();
                    while (it.hasNext()) {
                        String key = it.next();
                        GuideMonthlyBalance bean = new GuideMonthlyBalance();
                        bean.setMonth(key);
                        JsonArray jsonArray = JsonUtil.getJsonArrayFromMap(map.get(key));
                        for (int j = 0; j < jsonArray.size(); j++) {
                            GuideBalanceBean balanceBean = JsonUtil.getGson().fromJson(jsonArray.get(j).toString(), GuideBalanceBean.class);
                            bean.getList().add(balanceBean);
                        }
                        moneyMonthBeans.add(bean);
                    }
                    if (moneyMonthBeans.size() != 0) {
                        bindBalance();
                    } else {
                        bindEmpty();
                    }
                }
            }
        };
        ApiMethodGuide.getEarningsDetail(new SimpleLbObserver(listener,otherListener),this, FragmentEvent.DESTROY_VIEW);
    }

    private void sendRequestGetAlipayAccount() {
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    layoutAlipaySetting.setClickable(true);
                    accountBean = (AlipayAccountBean) JsonUtil.getObject(response.getReturnContent(), AlipayAccountBean.class);
                    if (accountBean.getReceiveAccount() != null) {
                        tvStatus.setText("已设置");
                    } else {
                        tvStatus.setText("未设置");
                    }
                }
            }
        };
        ApiMethodGuide.getAlipayAccount(new SimpleLbObserver(listener,otherListener),this, FragmentEvent.DESTROY_VIEW);
    }

    @Subscribe
    public void accountChange(AlipayAccountChangeEvent event) {
        sendRequestGetAlipayAccount();
    }

    @Subscribe
    public void refreshDivide(GuideDivideUpdateEvent event) {
        sendRequestGetMoneyList();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void userInfoChange(UserBeanEvent event) {
        balance = event.getUserBean().getAccountBalance();
        bindData();
    }

    @OnClick(R.id.layout_alipay_setting)
    void alipaySettings() {
        if (accountBean != null) {
            if (accountBean.getReceiveAccount() != null) {
                start(FragmentAlipayAccountDetail.newInstance(accountBean));
            } else {
                start(FragmentSetAlipayAccount.newInstance(AppConstant.SET_ALIPAY_ACCOUNT));
            }
        }
    }

    @OnClick(R.id.image_left)
    void leftClick() {
        pop();
    }


    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }

    private void bindEmpty() {
        noDataView.setVisibility(View.VISIBLE);
        mRecyclerView.setVisibility(View.GONE);
    }

    private void bindBalance() {
        noDataView.setVisibility(View.GONE);
        mRecyclerView.setVisibility(View.VISIBLE);
        mRecyclerView.setLayoutManager(new StickyHeaderLayoutManager());
        mAdapterMyMoney = new AdapterMyMoney(moneyMonthBeans, mContext);
        mRecyclerView.setAdapter(mAdapterMyMoney);
    }
}
